package com.vert.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Classname ClassLoder
 * @Description TODO
 * @Date 2022/6/5 18:06
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class MyClassLoader extends ClassLoader {

  public MyClassLoader(ClassLoader parent) {
    super(parent);
  }

  public Class loadClass(String url,String clazzName) throws ClassNotFoundException {
//    if(!"reflection.MyObject".equals(name))
//      return super.loadClass(name);

    try {
     // String url = "file:C:/data/projects/tutorials/web/WEB-INF/" +
     //   "classes/reflection/MyObject.class";
      URL myUrl = new URL(url);
      URLConnection connection = myUrl.openConnection();
      InputStream input = connection.getInputStream();
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      int data = input.read();

      while(data != -1){
        buffer.write(data);
        data = input.read();
      }

      input.close();

      byte[] classData = buffer.toByteArray();

      return defineClass(clazzName,
        classData, 0, classData.length);

    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
}
